package main

import (
	"fmt"
	"sync"
	"sync/atomic"
	"time"
)

func main() {
	chT6()
}

func chTest1() {
	ch := make(chan int, 1)
	ch <- 2
	n, ok := <-ch
	if ok {
		fmt.Printf("ch out :%d", n)
	}
	close(ch)
}

func chTest2() {
	ch := make(chan int, 10)
	for i := 1; i <= 10; i++ {
		ch <- i
	}
	close(ch)

	//阻塞型的遍历方式
	for x := range ch {
		fmt.Print(x)
	}
}

func chTest3() {
	ch := make(chan int)
	go func(ch chan int) {
		ch <- 3
	}(ch)
	fmt.Print(<-ch)
}

//任意型別數值
func chTest4() {
	ch := make(chan interface{})
	go func(ch chan interface{}) {
		for i := 1; i <= 10; i++ {
			ch <- i
		}

		ch <- "haha"
		close(ch)
	}(ch)

	for v := range ch {
		fmt.Print(v)
	}
}

func chTest5() {
	var n int64
	var wg sync.WaitGroup
	for i := 1; i <= 1000; i++ {
		wg.Add(1)
		go func() {
			atomic.AddInt64(&n, 2)
			//n++
			wg.Done()
		}()
	}
	wg.Wait()

	fmt.Print(n)
}

//ch select
func chT6() {
	ch := make(chan int, 1)
	//ch <- 1

	//to := make(chan bool,1)
	//go func() {
	//	time.Sleep(5 * time.Second)
	//	to <- true
	//}()

	select {
	case <-ch:
		println("random 1")
	case <-ch:
		println("rand 2")
	//default:
	//	println("default")
	//case <-to:
	//	println("time out 1")
	case <-time.After(time.Second * 2):
		println("time out 2")

	}
}
